package main

import (
	"common/config"
	"common/logs"
	"common/metrics"
	"connector/app"
	"connector/game"
	"context"
	"fmt"
	"github.com/spf13/cobra"
	"log"
	"os"
)

var rootCmd = &cobra.Command{
	Use:   "connector",
	Short: "connector 管理连接，session以及路由请求",
	Long:  `connector 管理连接，session以及路由请求`,
	Run: func(cmd *cobra.Command, args []string) {
	},
	PostRun: func(cmd *cobra.Command, args []string) {
	},
}

var (
	configFile    string
	gameConfigDir string
	serverId      string
)

func init() {
	rootCmd.Flags().StringVar(&configFile, "config", "application.yml", "app config yml file")
	rootCmd.Flags().StringVar(&gameConfigDir, "gameDir", "../config", "game config dir")
	// serverId 必填
	rootCmd.Flags().StringVar(&serverId, "serverId", "connector001", "app server id， required")
	_ = rootCmd.MarkFlagRequired("serverId")
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		log.Println(err)
		os.Exit(1)
	}
	// 1. 加载配置文件
	config.InitConfig(configFile)
	game.InitConfig(gameConfigDir)
	// 2. 初始化日志
	logs.InitLog()
	// 3. 启动监控
	metric := config.Conf.Metric
	if metric.Enable {
		go func() {
			if err := metrics.Serve(fmt.Sprintf("0.0.0.0:%d", metric.Port)); err != nil {
				logs.Error("start metrics error: %v \n", err)
			}
		}()
	}
	// 4. 启动服务
	if err := app.Run(context.Background(), serverId); err != nil {
		logs.Fatal(err.Error())
	}
}
